<?php
require_once "../../_inc/funct.xml2array.php";
$isReloadable = false;
require_once("../../../pers/inc.config.php");
require_once('../../_inc/inc.session.php');
require_once('../../_inc/funct.html.php');
require_once('../../_inc/funct.tabDati.php');
require_once('../../_inc/class.rglDocGen.php');

$sSql = "SELECT b.file_caricato, b.str_def_dati, b.id_set_dati, a.cod_fisc, a.rag_soc, b.data_rif "
	." FROM rgl_bilancio b "
	." LEFT JOIN rgl_azienda a ON b.id_azienda = a.id_azienda" 
	." WHERE b.id_bil = ".reqVarInt('id');
$objDB->query($sSql,'readBilOrig');
$acB = $objDB->fetch('readBilOrig');
if (!$acB) {
	die("id.bil. '$idBil' non trovato ");
}
$aDefDati = unsgzu($acB['str_def_dati']);
$aCodFonte = array();
foreach($aDefDati as $kX => $aX) {
	if ($aX['tipo_tab_dati']!= 1 || $aX['cod_fonte'] == '') continue;
	$codFonte = str_replace('itcc-ci:','',$aX['cod_fonte']);
	if (!isset($aCodFonte[$codFonte]))
		$aCodFonte[$codFonte] = $aX['cod_dato'];
	else 
		$aCodFonte[$codFonte] .= ", ".$aX['cod_dato'];
}
//die("<pre>".print_r($aCodFonte,1)."</pre>");
$aXml = xml2array(gzuncompress($acB['file_caricato']),array('withAttr'=>true));
//die(x2vPrint($aXml));


$oDoc = new rglDocGen();
$oDoc->maxCol = 40;
$oDoc->pdfIntestaz = "XBRL - ".$acB['rag_soc']."_".$acB['data_rif'];
$oDoc->bottomLeftText = date("d/m/Y H:i:s")." (".$_SERVER['HTTP_HOST'].RGL_URL_ROOT.")";

$oDoc->nuovaRigaNP();
$aCol = array('cla'=>'lab1','col'=>20,'alg'=>'C','txt'=>'Tag');
$oDoc->setColNP($aCol);
$aCol = array('cla'=>'lab1','col'=>10,'alg'=>'C','txt'=>'Attributi');
$oDoc->setColNP($aCol);
$aCol = array('cla'=>'lab1','col'=>10,'alg'=>'C','txt'=>'Valore');
$oDoc->setColNP($aCol);

$oDoc->forzaLabNP();

foreach(rglVx($aXml,'aXml','xbrl',0) as $tagX => $aX) {
	for($kX=0;$kX<99999;$kX++) {
		if (!isset($aX[$kX])) break;
		scriviTag($tagX,$aX,$kX,$oDoc,$aCodFonte);
	}
}

$sPdf = $oDoc->genPdf(array('orientaPagina'=>'P'));
headerDownLoad(strlen($sPdf),"xblr_".$acB['cod_fisc']."_".$acB['data_rif'].".pdf");
echo $sPdf;
exit();

function scriviTag($tag,$aT,$kT,&$oDoc,&$aCodFonte) {
	$oDoc->nuovaRiga();
	$oDoc->setParRiga('labNP',true);
	$aCol = array('cla'=>'txt1','col'=>20,'alg'=>'L','txt'=>$tag);
	$oDoc->setCol($aCol);
	$sAtt = '';
	if (is_array(rglVx($aT,$kT.'A'))) {
		foreach(rglVx($aT,$kT.'A') as $kA => $vA) {
			$sAtt .= $kA.'='.$vA."\n";			
		}
	}
	$aCol = array('cla'=>'txt1','col'=>10,'alg'=>'L','txt'=>$sAtt);
	$oDoc->setCol($aCol);
	if (is_array($aT[$kT])) $val = '';
	else $val = $aT[$kT];
	if (isset($aCodFonte[$tag])) {
		$val .= "\n(".$aCodFonte[$tag].")";
	}
	$aCol = array('cla'=>'txt1','col'=>10,'alg'=>'L','txt'=>$val);
	$oDoc->setCol($aCol);	
}
